import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
import { publishPresets, users } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';

// 获取单个预设
export async function GET(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({
        success: false,
        error: '请先登录',
      }, { status: 401 });
    }

    // 获取用户信息
    const user = await db.query.users.findFirst({
      where: eq(users.email, session.user.email),
    });

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '用户不存在',
      }, { status: 404 });
    }

    // 获取预设
    const preset = await db.query.publishPresets.findFirst({
      where: and(
        eq(publishPresets.id, id),
        eq(publishPresets.userId, user.id)
      ),
    });

    if (!preset) {
      return NextResponse.json({
        success: false,
        error: '预设不存在',
      }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      data: preset,
    });
  } catch (error) {
    console.error('获取预设失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取预设失败',
    }, { status: 500 });
  }
}

// 更新预设
export async function PUT(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({
        success: false,
        error: '请先登录',
      }, { status: 401 });
    }

    // 获取用户信息
    const user = await db.query.users.findFirst({
      where: eq(users.email, session.user.email),
    });

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '用户不存在',
      }, { status: 404 });
    }

    // 检查预设是否存在
    const existingPreset = await db.query.publishPresets.findFirst({
      where: and(
        eq(publishPresets.id, id),
        eq(publishPresets.userId, user.id)
      ),
    });

    if (!existingPreset) {
      return NextResponse.json({
        success: false,
        error: '预设不存在',
      }, { status: 404 });
    }

    const body = await request.json();
    const {
      name,
      authorName,
      autoGenerateDigest,
      headerContent,
      footerContent,
      isDefault,
      platformConfig,
    } = body;

    // 如果设置为默认预设，先取消同平台其他预设的默认状态
    if (isDefault && !existingPreset.isDefault) {
      await db.update(publishPresets)
        .set({ isDefault: false })
        .where(and(
          eq(publishPresets.userId, user.id),
          eq(publishPresets.platform, existingPreset.platform)
        ));
    }

    // 更新预设
    await db.update(publishPresets)
      .set({
        name,
        authorName,
        autoGenerateDigest,
        headerContent,
        footerContent,
        isDefault,
        platformConfig: platformConfig ? JSON.stringify(platformConfig) : null,
        updatedAt: new Date(),
      })
      .where(and(
        eq(publishPresets.id, id),
        eq(publishPresets.userId, user.id)
      ));

    // 获取更新后的预设
    const updatedPreset = await db.query.publishPresets.findFirst({
      where: eq(publishPresets.id, id),
    });

    return NextResponse.json({
      success: true,
      data: updatedPreset,
      message: '预设更新成功',
    });
  } catch (error) {
    console.error('更新预设失败:', error);
    return NextResponse.json({
      success: false,
      error: '更新预设失败',
    }, { status: 500 });
  }
}

// 删除预设
export async function DELETE(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await context.params;
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({
        success: false,
        error: '请先登录',
      }, { status: 401 });
    }

    // 获取用户信息
    const user = await db.query.users.findFirst({
      where: eq(users.email, session.user.email),
    });

    if (!user) {
      return NextResponse.json({
        success: false,
        error: '用户不存在',
      }, { status: 404 });
    }

    // 检查预设是否存在
    const existingPreset = await db.query.publishPresets.findFirst({
      where: and(
        eq(publishPresets.id, id),
        eq(publishPresets.userId, user.id)
      ),
    });

    if (!existingPreset) {
      return NextResponse.json({
        success: false,
        error: '预设不存在',
      }, { status: 404 });
    }

    // 删除预设
    await db.delete(publishPresets)
      .where(and(
        eq(publishPresets.id, id),
        eq(publishPresets.userId, user.id)
      ));

    return NextResponse.json({
      success: true,
      message: '预设删除成功',
    });
  } catch (error) {
    console.error('删除预设失败:', error);
    return NextResponse.json({
      success: false,
      error: '删除预设失败',
    }, { status: 500 });
  }
}
